package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.ShopService;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    WeChatProperties weChatProperties;
    @Autowired
    UserMapper userMapper;

    private final String wxUrl = "https://api.weixin.qq.com/sns/jscode2session";

    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //请求wx登录接口 获得openid
        String openid = getOpenid(userLoginDTO.getCode());

        //判断openid是否存在
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED + "用户端请求 唯一凭证不存在");

        }
        //判断是否为新用户
        User user = userMapper.getUserByOpenId(openid);

        //不是的话存入数据库
        if (user == null) {
            //重新赋值
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.addUser(user);
        }

        //返回user
        return user;
    }

    private String getOpenid(String code) {

        String appid = weChatProperties.getAppid();
        String secret = weChatProperties.getSecret();

        //请求参数
        HashMap<String, String> param = new HashMap<>();
        param.put("appid", appid);
        param.put("secret", secret);
        param.put("js_code", code);
        param.put("grant_type", "authorization_code");
        //发送请求
        String json = HttpClientUtil.doGet(wxUrl, param);
        log.info("wx请求返回信息>: {}", json);

        //解析
        JSONObject jsonObject = JSON.parseObject(json);

        return jsonObject.getString("openid");

    }


}
